/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nanosl.norg.general.gui;

import com.nanosl.lib.db.Manager;
import com.nanosl.norg.ent.PhoneType;
import com.nanosl.norg.util.NTopComponent;
import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.table.DefaultTableModel;
import org.netbeans.api.settings.ConvertAsProperties;
import org.netbeans.spi.actions.AbstractSavable;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.UndoRedo;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle.Messages;
import org.openide.util.lookup.AbstractLookup;
import org.openide.util.lookup.InstanceContent;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
    dtd = "-//com.nanosl.credit.editor//PhoneTypeEditor//EN",
autostore = false)
@TopComponent.Description(
    preferredID = "PhoneTypeEditorTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Editor", id = "com.nanosl.credit.editor.PhoneTypeEditorTopComponent")
@ActionReference(path = "Menu/Editor", position = 6)
@TopComponent.OpenActionRegistration(
    displayName = "#CTL_PhoneTypeEditorAction",
preferredID = "PhoneTypeEditorTopComponent")
@Messages({
    "CTL_PhoneTypeEditorAction=PhoneTypeEditor",
    "CTL_PhoneTypeEditorTopComponent=PhoneTypeEditor Window",
    "HINT_PhoneTypeEditorTopComponent=This is a PhoneTypeEditor window"
})
public final class PhoneTypeEditorTopComponent extends NTopComponent implements LookupListener {

    private DefaultTableModel phoneTypeTableModel;
    Manager mananger = Manager.getInstance();

    public static void display() {
        PhoneTypeEditorTopComponent tc = (PhoneTypeEditorTopComponent) WindowManager.getDefault().findTopComponent("PhoneTypeEditorTopComponent");
        tc.open();
        tc.requestActive();
        tc.requestFocus();
    }

    public PhoneTypeEditorTopComponent() {
        initComponents();
        phoneTypeTableModel = (DefaultTableModel) phoneTypeTable.getModel();
        setName(Bundle.CTL_PhoneTypeEditorTopComponent());
        setToolTipText(Bundle.HINT_PhoneTypeEditorTopComponent());

        instanceContent = new InstanceContent();
        associateLookup(new AbstractLookup(instanceContent));
        codeTextField.getDocument().addUndoableEditListener(UndoRedoManager);
        typeTextField.getDocument().addUndoableEditListener(UndoRedoManager);
        codeTextField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                modify();
            }
        });
        typeTextField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                modify();
            }
        });
    }

    private void fillPhoneTypeTable() {
        phoneTypeTableModel.setRowCount(0);
        Collection<PhoneType> collectionCenters = mananger.find(PhoneType.class);
        for (Iterator<PhoneType> it = collectionCenters.iterator(); it.hasNext();) {
            PhoneType phoneType = it.next();
            Object[] row = {
                phoneType,
                phoneType.getType()
            };
            phoneTypeTableModel.addRow(row);
        }
    }

    private void modify() {
        if (getLookup().lookup(PhoneTypeEditorTopComponent.PhoneTypeSavable.class) == null) {
            instanceContent.add(new PhoneTypeEditorTopComponent.PhoneTypeSavable());
        }
    }

    @Override
    public void componentOpened() {
        result = WindowManager.getDefault().findTopComponent("EntityExplorerTopComponent").getLookup().lookupResult(PhoneType.class);
        result.addLookupListener(this);
        resultChanged(new LookupEvent(result));
        fillPhoneTypeTable();
        codeTextField.requestFocus();
    }

    @Override
    public void componentClosed() {
        result.removeLookupListener(this);
        result = null;
    }

    @Override
    public void resultChanged(LookupEvent lookupEvent) {
        Lookup.Result r = (Lookup.Result) lookupEvent.getSource();
        Collection<PhoneType> coll = r.allInstances();

        if (!coll.isEmpty()) {
            PhoneTypeEditorTopComponent tc = (PhoneTypeEditorTopComponent) WindowManager.getDefault().findTopComponent("PhoneTypeEditorTopComponent");
            tc.resetFields();
            tc.open();
            tc.requestVisible();
//            tc.requestActive();
            for (PhoneType phoneType : coll) {
                codeTextField.setText(phoneType.getCode());
                typeTextField.setText(phoneType.getType());
            }
        } else {
            codeTextField.setText("");
            typeTextField.setText("");
        }
    }

    public void resetFields() {
        codeTextField.setText("");
        typeTextField.setText("");
        codeTextField.requestFocus();
    }

    @Override
    public UndoRedo getUndoRedo() {
        return UndoRedoManager;
    }

    private class PhoneTypeSavable extends AbstractSavable {

        String code, type;

        PhoneTypeSavable() {
            register();
        }

        @Override
        protected String findDisplayName() {
            code = codeTextField.getText();
            type = typeTextField.getText();
            return "( " + code + " ) " + type;
        }

        @Override
        protected void handleSave() throws IOException {

            code = codeTextField.getText().trim();
            type = typeTextField.getText().trim();
            if (code.equals("") || type.equals("")) {
            }
            NotifyDescriptor.Confirmation message = new NotifyDescriptor.Confirmation(
                    "Do you want to save \n ( " + code + " ) " + type + "?", NotifyDescriptor.OK_CANCEL_OPTION, NotifyDescriptor.QUESTION_MESSAGE);
            Object result = DialogDisplayer.getDefault().notify(message);
//When user clicks "Yes", indicating they really want to save,
//we need to disable the Save action,
//so that it will only be usable when the next change is made.
            if (NotifyDescriptor.YES_OPTION.equals(result)) {

                //Handle the save here...
                Manager manager = Manager.getInstance();
                PhoneType phoneType = new PhoneType(code);
                phoneType.setType(type);
                manager.update(phoneType);
                resetFields();
                fillPhoneTypeTable();
                tc().instanceContent.remove(this);
                unregister();
            }
        }

        PhoneTypeEditorTopComponent tc() {
            return PhoneTypeEditorTopComponent.this;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof PhoneTypeSavable) {
                PhoneTypeSavable m = (PhoneTypeSavable) obj;
                return tc() == m.tc();
            }
            return false;
        }

        @Override
        public int hashCode() {
            return tc().hashCode();
        }
    }
    private Lookup.Result result = null;
    private UndoRedo.Manager UndoRedoManager = new UndoRedo.Manager();
    private InstanceContent instanceContent;

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        codeTextField = new javax.swing.JTextField();
        typeTextField = new javax.swing.JTextField();
        saveButton = new javax.swing.JButton();
        clearButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        phoneTypeTable = new javax.swing.JTable();

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(PhoneTypeEditorTopComponent.class, "PhoneTypeEditorTopComponent.jLabel1.text_1")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(PhoneTypeEditorTopComponent.class, "PhoneTypeEditorTopComponent.jLabel2.text_1")); // NOI18N

        codeTextField.setText(org.openide.util.NbBundle.getMessage(PhoneTypeEditorTopComponent.class, "PhoneTypeEditorTopComponent.codeTextField.text_1")); // NOI18N
        codeTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                codeTextFieldActionPerformed(evt);
            }
        });

        typeTextField.setText(org.openide.util.NbBundle.getMessage(PhoneTypeEditorTopComponent.class, "PhoneTypeEditorTopComponent.typeTextField.text_1")); // NOI18N
        typeTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                typeTextFieldActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(saveButton, org.openide.util.NbBundle.getMessage(PhoneTypeEditorTopComponent.class, "PhoneTypeEditorTopComponent.saveButton.text_1")); // NOI18N
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(clearButton, org.openide.util.NbBundle.getMessage(PhoneTypeEditorTopComponent.class, "PhoneTypeEditorTopComponent.clearButton.text_1")); // NOI18N
        clearButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearButtonActionPerformed(evt);
            }
        });

        phoneTypeTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Code", "Type"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        phoneTypeTable.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                phoneTypeTableKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(phoneTypeTable);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(codeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(typeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(clearButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(saveButton)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(codeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(typeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(saveButton)
                    .addComponent(clearButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void codeTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_codeTextFieldActionPerformed
        String code = codeTextField.getText().trim();
        if (!code.equals("")) {
            PhoneType phoneType = Manager.getInstance().find(PhoneType.class, code);
            typeTextField.setText(phoneType != null ? phoneType.getType() : "");
            codeTextField.setBackground(Color.WHITE);
            typeTextField.requestFocus();
        } else {
            errorField(codeTextField);
        }
    }//GEN-LAST:event_codeTextFieldActionPerformed

    private void typeTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_typeTextFieldActionPerformed
        if (isText(typeTextField.getText().trim())) {
            typeTextField.setBackground(Color.WHITE);
            try {
                new PhoneTypeSavable().handleSave();
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        } else {
            errorField(typeTextField);
        }
    }//GEN-LAST:event_typeTextFieldActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        if (codeTextField.getText().trim().equals("") || typeTextField.getText().trim().equals("")) {
            showError("Invalid Phone Type");
            codeTextField.requestFocus();

        } else {
            try {
                new PhoneTypeSavable().handleSave();
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearButtonActionPerformed
        resetFields();
    }//GEN-LAST:event_clearButtonActionPerformed

    private void phoneTypeTableKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_phoneTypeTableKeyPressed

        if (evt.getKeyCode() == 127) {
            PhoneType phoneType = (PhoneType) phoneTypeTable.getValueAt(phoneTypeTable.getSelectedRow(), 0);
            if (confirm("Are you sure to delete " + phoneType + " ?")) {
                if (manager.delete(PhoneType.class, phoneType.getCode())) {
                    fillPhoneTypeTable();
                } else {
                    showError("Unable to delete " + phoneType);
                }
            }
        }
    }//GEN-LAST:event_phoneTypeTableKeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton clearButton;
    private javax.swing.JTextField codeTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable phoneTypeTable;
    private javax.swing.JButton saveButton;
    private javax.swing.JTextField typeTextField;
    // End of variables declaration//GEN-END:variables

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }
}
